import React, { Component } from "react";
import { Form, Input, Table, Button, Divider,Row,Col ,Select, DatePicker, Modal} from "antd";

import Content from "../../components/Content/Content";
import moment from "moment";
import { rest } from "lodash";

const { Item } = Form;
const { Option } = Select;
const InputGroup = Input.Group;
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    fixed: 'left', 
    width:90,
    editable: false,
  },      
  {
    title: '筛选菌株编号', 
    dataIndex: 'sxjj_id',
    fixed: 'left',
    width:190,
  },
  {
    title: '样品编号',
    dataIndex: 'yp_id',
    fixed: 'left',
    width:190,
  },
  {
    title: '编号类型',
    dataIndex: 'asdyp_type',
    fixed: 'left',
    width:190,
    render: (text, record) => (
      <Select defaultValue={text}
      mode="tags"
      style={{ width: "100%" }}
      onChange={(value) => this.setState({asdyp_type: value[0]})}
      tokenSeparators={[","]}
      showArrow={true}
    >
        <Option value="f_fjypid">发酵样品编号</Option>
        <Option value="lf_id">流份编号</Option>
        <Option value="ctp_id">粗提品编号</Option>
        <Option value="hhw_id">化合物编号</Option>
      </Select>
    )
  },
  {
    title: '筛选方法名称',
    dataIndex: 'm_name',
  },
  {
    title: '筛选样品初筛检测值',
    dataIndex: 'as_jcz',
  },
  {
    title: '初筛空白对照',
    dataIndex: 'as_kbdz',
    editable: true,
  },
  {
    title: '初筛阳性对照',
    dataIndex: 'as_yxdz',
    editable: true,
  },
  {
    title: '初筛阴性对照',
    dataIndex: 'as_yydz',
    editable: true,
  },
  {
    title: '初筛样品活性',
    dataIndex: 'as_yphx',
    editable: true,
  },
  {
    title: '初筛结果录入时间',
    dataIndex: 'as_time',
  },
  {
    title: '初筛阳性判定值',
    dataIndex: 'as_pdz',
  },
  {
    title: '初筛结果',
    dataIndex: 'as_jg',
  },
];

const data = [];

/**
for (let i = 0; i < 22; i++) {
  data.push({
    id: i,
    as_pdz: `ACCC000${i}`,
    as_jg: 666666666,
  });
}
 */

class Query_mediumForm extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    selectedRowKeys: [], // Check here to configure the default column

    dataSource: data, 
    count: 1,

    asdyp_type:'', // 样品编号类型

    viewData: {},
    newData: {},

    searchParams : {},

    loading: true,
    pd_loading: false,
    loading_out: false,
    re_loading: false,

    pageNum: 1,
    pageSize: 100
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);
    
    const url = global.api.activityscreeningDecide;

    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search:{}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  } 

  doPanDing = () => {
    this.setState({ pd_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [], 
        pd_loading: false
      });
    }, 1000);

    let as_yphx = this.state.newData.as_yphx ;
    let as_pdz  = this.state.newData.as_pdz  ;
    let as_jg = '--';
    if( as_yphx > as_pdz ) {
      as_jg = '阳性';
    } else {
      as_jg = '阴性';
    }

    this.state.newData.as_jg = as_jg;

    let dataSource = this.state.dataSource;
    dataSource.push(this.state.newData);

    const url = global.api.activityscreeningDecide;
    return global.network.post(url, this.state.newData)
    .then(res => {  
      this.loadData(1);

      Modal.success({
        content: '保存成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '保存出错，请检查传入的参数是否已经填写！',
      });
    }) 

  };

  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  onSubmit = evt => {
    evt.preventDefault();
    const { onSubmit } = this.props;
    onSubmit && onSubmit();
  };

  // 导出到本地
  outToLocal = () => {
    this.setState({ loading_out: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading_out: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   
 
  };

  // 复筛
  reDecide = () => {
    this.setState({ re_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        re_loading: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        
        /**
        // 把数据存储到复筛表
        初筛数据转入复筛的实现：
        A、选定初筛判定表中的数据；
        B、获得相关数据的sxjj_id\asdyp_type\yp_id三个字段数据；
        C、上传到复筛输入表中，除上述三个字段外，其他为空。
        D、返回“已将该菌株放入筛录入表”完成。
          */

        record.id = moment(new Date()).format('ssSSS');
        record.scdyp_type = record.asdyp_type;
        record.sc_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

        const url = global.api.secondarycreeningEntering;

        return global.network.post(url, record)
        .then(res => {
          Modal.success({
            content: '成功了！'
          })
        })
        .catch(err => {
          Modal.error({
            content: '出错了！'
          })
        }) 

      }
    }   
 
  };

  loadDataById = e => {
    let id = e.target.value;
    this.state.newData.sxjj_id  = id;

    const url = global.api.secondarycreeningEntering + id + '/';

    return global.getdata.get(url)
    .then(res => {
      console.info(res);
      this.setState({
        newData: rest.results[0]
      })
    })
    .catch(err => {
     
    }) 
  }

  render() {
    const { selectedRowKeys, loading_out, re_loading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    const hasSelected = selectedRowKeys.length > 0;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      }
    };

    return (
      <div>
        <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false} style={{ borderBottom: "20px solid #f0f2f5" }}>
          <Item label="筛选菌株编号">
                <Input defaultValue={this.state.newData.sxjj_id }  onChange={(e) => this.loadDataById(e)} />
          </Item>
          <Item label="筛选方法名称">
                <Input defaultValue={this.state.newData.m_name } onChange={e => this.state.newData.m_name  = e.target.value } />
          </Item>
          <Item label="筛选方法编号">
                <Input defaultValue={this.state.newData.m_id } onChange={e => this.state.newData.m_id  = e.target.value } />
          </Item>
          <Item label="录入时间">
                <DatePicker
                  onChange={(value, dateString) => this.state.newData.as_time  = dateString}
                  style={{ width: "100%" }}
                />     
          </Item>
          <Item label="样品编号">
                <Input style={{ width: "60%" }} defaultValue={this.state.newData.yp_id } onChange={e => this.state.newData.yp_id  = e.target.value } />
                <InputGroup compact style={{ width: "40%" }}>
                  <Select
                    // mode="tags"
                    style={{ width: "100%" }}
                    onChange={value => this.state.newData.asdyp_type  = value[0]}
                    tokenSeparators={[","]}
                    showArrow={true}
                  >
        <Option value="f_fjypid">发酵样品编号</Option>
        <Option value="lf_id">流份编号</Option>
        <Option value="ctp_id">粗提品编号</Option>
        <Option value="hhw_id">化合物编号</Option>
                  </Select>
                </InputGroup>
          </Item>
          <Item label="初筛阳性判定值">
                <Input defaultValue={this.state.newData.as_pdz } onChange={e => this.state.newData.as_pdz  = e.target.value } />
          </Item>
            <Item wrapperCol={{ span: 12, offset: 5 }}>
          <Row guuter={16}>
            <Col span={5}>
              <Button type="primary" htmlType="submit" onClick={this.doPanDing} loading={this.state.pd_loading}>
              判定
              </Button>
            </Col>
          </Row>
        </Item>
            
        </Form>
        <Button type="primary" htmlType="submit" style={{marginLeft:'24px', marginTop: '20px'}} onClick={this.outToLocal} disabled={!hasSelected} loading={loading_out}>
              导出
        </Button>
        <Button type="primary" htmlType="submit" style={{marginLeft:'50px'}} onClick={this.reDecide} disabled={!hasSelected} loading={re_loading}>
              复筛
        </Button>
        <span style={{ marginLeft: 8 }}>
            {hasSelected ? `选中 ${selectedRowKeys.length} 条` : ''}
          </span>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={this.state.dataSource}
          bordered
          style={{ marginLeft: 12 }}
          scroll={{ x: 2000, y: 300 }}
        />
      </div>
    );
  }
}
const WrapperedQuery_mediumForm = Form.create({
  name: "query medium"
})(Query_mediumForm);

class ManageQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = () => {
    const { form } = this.form.props;
    form.validateFields((errs, values) => {
      console.log(errs, values);
    });
  };
  render() {
    return (
      <Content>
        <WrapperedQuery_mediumForm
          wrappedComponentRef={ref => (this.form = ref)}
          onSubmit={this.onSubmit}
        />
      </Content>
    );
  }
} 

export default ManageQuery;
